package com.demospringboot.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demospringboot.system.entity.User;
import com.demospringboot.system.mapper.UserMapper;
import com.demospringboot.system.service.IUserService;
import com.demospringboot.system.entity.dto.LoginDto;
import com.demospringboot.system.entity.dto.UserDto;
import com.demospringboot.utils.JwtUtil;
import com.demospringboot.utils.PasswordUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Override
    public UserDto login(LoginDto loginDto) {
        // 1. 根据用户名查找用户
        User user = lambdaQuery().eq(User::getUsername, loginDto.getUsername()).one();
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        // 2. 校验密码
        if (!PasswordUtils.match(loginDto.getPassword(), user.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        // 3. 生成 token
        String token = JwtUtil.createToken(user.getUsername(), user.getRole().name());
        // 4. 封装 UserDto
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(user, userDto);
        userDto.setToken(token);
        return userDto;
    }
} 